#include "slicemainwindow.h"
#include "ui_slicemainwindow.h"

SliceMainWindow::SliceMainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::SliceMainWindow)
{
    ui->setupUi(this);
    iniUI();
}

SliceMainWindow::~SliceMainWindow()
{
    delete ui;
}

void SliceMainWindow::iniUI()
{
    fLabCurFile = new QLabel;
    fLabCurFile->setMinimumWidth(150);
    fLabCurFile->setText("当前切片：");
    ui->statusbar->addWidget(fLabCurFile);
}

void SliceMainWindow::initSliceWidget(std::shared_ptr<STLReader> sp_stl_reader, const SliceInfo &slice_info)
{
    m_sp_stl_reader = sp_stl_reader;

    if(m_sp_sliceWidget)
        m_sp_sliceWidget->deleteLater();

    m_sp_sliceWidget = std::make_shared<STLSliceWidget>(sp_stl_reader, slice_info, this);

    setCentralWidget(m_sp_sliceWidget.get());

    connect(m_sp_sliceWidget.get(), &STLSliceWidget::sendSliceNumberStatus, this, &SliceMainWindow::updateCurrentFileLabel);

    m_sp_sliceWidget->show();
}

void SliceMainWindow::updateCurrentFileLabel(const qsizetype &cur_slice_indice, const qsizetype &total_slice_amount)
{
    fLabCurFile->setText(QString("切片: %1/%2").arg(cur_slice_indice).arg(total_slice_amount));
}

void SliceMainWindow::createContoursWindow(ContourInfo contour_info)
{
    // 创建轮廓窗口（设置父对象为切片控件）
    m_sp_contourWidget = std::make_shared<ContourMainWindow>(m_sp_sliceWidget.get());

    // 初始化切片控件
    m_sp_contourWidget->initContourWidget(m_sp_stl_reader, contour_info);

    // 设置窗口属性
    m_sp_contourWidget->setWindowTitle("轮廓视图");
    m_sp_contourWidget->setWindowFlags(Qt::Window);
    m_sp_contourWidget->resize(this->width(), this->height());

    // 显示窗口
    m_sp_contourWidget->show();
}

void SliceMainWindow::on_actionContourExtraction_triggered()
{
    // 创建切片窗口（设置父对象为模型控件）
    m_sp_contourWidget = std::make_shared<ContourMainWindow>(m_sp_sliceWidget.get());

    // 设置窗口属性
    m_sp_contourWidget->setWindowTitle("轮廓视图");
    m_sp_contourWidget->setWindowFlags(Qt::Window);
    m_sp_contourWidget->resize(this->width(), this->height());

    QVector3D camera_pos = m_sp_sliceWidget->getCurrentCameraPos();
    QVector3D plane_norm = camera_pos.normalized();
    QVector3D camera_up = m_sp_sliceWidget->getCurrentCameraUp();
    float camera_dis = camera_pos.length();
    float slice_depth = m_sp_sliceWidget->getCurrentSliceDepth();

    // 设置切片轮廓参数
    ContourInfo contour_info = {plane_norm, camera_up, camera_dis, slice_depth};

    // 初始化切片控件
    m_sp_contourWidget->initContourWidget(m_sp_stl_reader, contour_info);

    // 显示窗口
    m_sp_contourWidget->show();
}

void SliceMainWindow::on_actionGetAllContours_triggered()
{
    QVector<QVector<QVector<QPointF>>> all_contours = m_sp_sliceWidget->getModelContours2D();
    emit deliverAllContours(all_contours);
}
